﻿using System.Collections;
using System.Text;
using System.Text.RegularExpressions;
using BusinessLogic.BusinessRules;
using BusinessLogic.ClassFactory;
using Common;

namespace IssueCommon
{
    public class ArticleIssue : IssueBase
    {
        private Sections _Section;
        private Article _Article;
        private ArtSecRelation _ArtSec;

        private string _strParentPath = "";

        public string ParentPath
        {
            get { return _strParentPath; }
            set { _strParentPath = value; }
        }

        private string _strPageName = "";

        public string PageName
        {
            get { return _strPageName; }
            set { _strPageName = value; }
        }

        public ArticleIssue(int intCurrentSectionID, int intSecArtID, SessionUser sessionUser)
            : base()
        {
            base.SessionUser = sessionUser;
            int intSectionID = -1;
            Sections.FindSectionReferRoot(intCurrentSectionID,ref intSectionID);

            //设置是否栏目引用
            if (intCurrentSectionID != intSectionID)
            {
                IsRefer = true;
                CurrentSectionID = intCurrentSectionID;
            }

            SectionsFactory objSectionFactory = new SectionsFactory(_DBManager);
            _Section = objSectionFactory.Creator(intCurrentSectionID);

            ArtSecRelationFactory objASFactory = new ArtSecRelationFactory(_DBManager);
            _ArtSec = objASFactory.CreatorBySql("intSecArtID=" + intSecArtID + " and intSectionId=" + intSectionID);
            if (_ArtSec == null)
            {
                _ArtSec = objASFactory.CreatorBySql("intSecArtID=" + intSecArtID + " and intSectionId=" + intCurrentSectionID);
            }

            if (_ArtSec == null)
            {
                string strMsg = string.Format("未找到文章和栏目的关联数据,intSectionID={0}, intSecArtID={1}", intSectionID, intSecArtID);
                throw new Model.Common.CustomException(strMsg);
            }

            ArticleFactory objFactory = new ArticleFactory(_DBManager);
            _Article = objFactory.Creator(_ArtSec.DataItem.intArticleID);

            if (_Article == null)
            {
                string strMsg = string.Format("未找到文章数据,intSectionID={0}, intArticleID={1}", intSectionID, _ArtSec.DataItem.intArticleID);
                throw new Model.Common.CustomException(strMsg);
            }

            _intDefaultID = intSecArtID;
            _intDefaultASID = _ArtSec.DataItem.intSecArtID;
            _intDefaultParentID = intSectionID;
        }

        public ArticleIssue(int intCurrentSectionID, SessionUser sessionUser)
            : base()
        {
            base.SessionUser = sessionUser;
            SessionUser = sessionUser;
            int intSectionID = -1;
            Sections.FindSectionReferRoot(intCurrentSectionID, ref intSectionID);
            SectionsFactory objSectionFactory = new SectionsFactory(_DBManager);
            _Section = objSectionFactory.Creator(intCurrentSectionID);
            _Section.SessionUser = sessionUser;

            //设置是否栏目引用
            if (intCurrentSectionID != intSectionID)
            {
                IsRefer = true;
                CurrentSectionID = intCurrentSectionID;
            }

            _intDefaultParentID = intSectionID;
        }

        /// <summary>
        ///  发布指定文章时的构造函数
        /// </summary>
        /// <param name="intSectionID">栏目ID</param>
        /// <param name="intArtRecID">文章关联ID</param>
        public ArticleIssue(Sections objSection, int intArtRecID,SessionUser sessionUser)
            : base()
        {
            _Section = objSection;

            int intSectionID = -1;
            Sections.FindSectionReferRoot(_Section.DataItem.intSectionID, ref intSectionID);
            //设置是否栏目引用
            if (_Section.DataItem.intSectionID != intSectionID)
            {
                IsRefer = true;
                CurrentSectionID = intSectionID;
            }

            base.SessionUser = sessionUser;
            SessionUser = sessionUser;
            ParentPath = objSection.DataItem.IschvParentPathNull() ? "" : objSection.DataItem.chvParentPath;
            PageName = objSection.DataItem.IschvPageNameNull() ? "" : objSection.DataItem.chvPageName;
            ArtSecRelationFactory objFactory = new ArtSecRelationFactory(_DBManager);
            _ArtSec = objFactory.Creator(intArtRecID);
            if (_ArtSec == null)
            {
                string strMsg = string.Format("未找到文章,intSectionID={0}, intSecArtID={1}", intSectionID, intArtRecID);
                throw new Model.Common.CustomException(strMsg);
            }

            _intDefaultID = intArtRecID;
            _intDefaultParentID = _Section.DataItem.intSectionID;
        }

        public void CreateArticle(bool isIssuAll)
        {
            ArrayList intArticleIDs = _Section.GetIssueArticleIDs(isIssuAll);

            if (intArticleIDs != null)
            {
                for (int i = 0; i < intArticleIDs.Count; i++)
                {
                    using (SectionsFactory objSectionsFactory = new SectionsFactory())
                    {
                        try
                        {
                            Sections objSectionTemp = objSectionsFactory.CreatorBySql(" intSectionID=" + this._Section.DataItem.intSectionID + " or (intReferSectionID=" + this._Section.DataItem.intSectionID + " and intStateRefer=" + (int)Common.Utility.StateRefer.Yes + ")");
                            if (objSectionTemp != null)
                            {
                                for (int j = 0; j < objSectionTemp.Count; j++)
                                {
                                    using (ArticleIssue objArticleIssue = new ArticleIssue(objSectionTemp.DataItem.intSectionID, (int)intArticleIDs[i], base.SessionUser))
                                    {
                                        objArticleIssue.ParentPath = objSectionTemp.DataItem.IschvParentPathNull() ? "" : objSectionTemp.DataItem.chvParentPath;
                                        objArticleIssue.PageName = objSectionTemp.DataItem.IschvPageNameNull() ? "" : objSectionTemp.DataItem.chvPageName;
                                        objArticleIssue.IssueArticleContent();
                                    }
                                    objSectionTemp.SelectRow(j + 1);
                                }
                            }
                        }
                        catch(CustomException ex)
                        {
                            throw ex;
                        }
                        finally
                        {
                            objSectionsFactory.Dispose();
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 发布文章内容
        /// </summary>
        /// <param name="blnSetIssueStatus">是否设置文章发布状态，因为在文章预览时不能设置文章发布状态</param>
        /// <returns></returns>
        public void IssueArticleContent()
        {
            // 文章模板为空，采用栏目默认文章模板
            string strTemplate = string.Empty;
            if (_ArtSec.DataItem.IsintTmpIDNull() == true)
            {
                if (_Section.DataItem.IsintArticleTemIDNull() == true)
                {
                    string strMsg = string.Format("文章未指定模板，也无默认模板,文章ID={0}", this._Article.DataItem.intArticleID);
                    throw new Model.Common.CustomException(strMsg);
                }
                strTemplate = Template.GetTemplateString(_Section.DataItem.intArticleTemID,base.SessionUser);
            }
            else
            {
                strTemplate = Template.GetTemplateString(_ArtSec.DataItem.intTmpID, base.SessionUser);
            }

            string strHtml = string.Empty;
            // 解析模板插件的正则表达式
            string strRegexNoPage = string.Format("{0}([\\d\\D]+?){1}", Model.Common.Plugin.PluginBeginTag, Model.Common.Plugin.PluginEndTag);

            //if (AppConfig.GetIsShtml() == (int)Utility.IssueWebCodeLanguage.html)
            //{
            string strCommonRegexNoPage = string.Format("{0}([\\d\\D]+?){1}", Model.Common.Plugin.CommonPluginBeginTag, Model.Common.Plugin.CommonPluginEndTag);
            // 将模板文件中的公共插件替换，还原整个网页
            strHtml = Regex.Replace(strTemplate, strCommonRegexNoPage, new MatchEvaluator(base.ReplaceCommonPlugin), RegexOptions.IgnoreCase);
            strHtml = Regex.Replace(strHtml, strRegexNoPage, new MatchEvaluator(base.ReplacePlugin), RegexOptions.IgnoreCase);
            //}
            //else
            //{
            //    // 将模板文件中的插件部分用数据库中的真实数据替换
            //    strHtml = Regex.Replace(strTemplate, strRegexNoPage, new MatchEvaluator(base.ReplacePlugin), RegexOptions.IgnoreCase);
            //}
               string strFilePath="";
               if (SessionUser.EnableParentPath)
               {
                   string strPath = "";
                   string strName = "";
                   if (this.ParentPath == "" && this.PageName == "")
                   {
                       strPath = "ahtml\\";
                       strName = "A__"+(IsRefer==true?CurrentSectionID+"_":"");
                   }
                   else
                   {
                       strPath = this.ParentPath == "" ? "shtml\\" : ( this.ParentPath == "/" ?"":this.ParentPath + "\\");
                       strName = this.PageName + "_A__" + (IsRefer == true ? CurrentSectionID + "_" : "");
                   }
                   if (SessionUser.WebSiteLevel != 1)
                   {
                       strPath = SessionUser.VartualPath + "\\" + strPath;
                   }
                   strFilePath = string.Format("{0}/{1}{2}.{3}", base.SessionUser.IssuePath + strPath, strName, this._ArtSec.DataItem.intSecArtID, AppConfig.GetWebFileType());
                   strHtml = Htmlhandler.HandlerHtmlElementPath(strHtml, this.SessionUser);
               }
               else
               {
                   strFilePath = string.Format("{0}/A__{1}.{2}", base.SessionUser.IssuePath + "\\ahtml\\", (IsRefer==true?CurrentSectionID+"_":"")+this._ArtSec.DataItem.intSecArtID, AppConfig.GetWebFileType());
               }
            base.GenerateHtmlFile(strFilePath, strHtml);
            // 设置文章发布状态为已发布
            this._ArtSec.SetArticleIssueStatus(this._intDefaultParentID, true);
        }

        /// <summary>
        /// 获取发布的文章ID
        /// </summary>
        /// <param name="IsReIssue">是否重新发布</param>
        /// <returns>文章数量</returns>
        public int GetIssueArticleCount(bool IsReIssue)
        {
            StringBuilder strSql = new StringBuilder();
            int intReturn = 0;
            //strSql.Append("select * from Article where intArticleID in(");
            strSql.AppendFormat("select * from ArtSecRelation where intSectionID={0}", this._Section.DataItem.intSectionID);
            //strSql.Append(")");
            if (!IsReIssue)
            {
                strSql.AppendFormat(" and intState={0}", (int)Utility.ArticleState.NoIssue);
            }
            using (ArtSecRelationFactory objFactory = new ArtSecRelationFactory(_DBManager))
            {
                intReturn = objFactory.QueryByCompletionSql(strSql.ToString());
            }
            return intReturn;
        }
    }
}